# -*- coding: utf-8 -*-
import re
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template.context import RequestContext

from snipperize.snippet.models import Snippet
from snipperize.utils import json_response

import settings

def policy(request):
    return render_to_response('support/policy.html', context_instance=RequestContext(request))

def about(request):
    return render_to_response('support/about.html', context_instance=RequestContext(request))

def recent_updates(request):
    return render_to_response('support/recent_updates.html', context_instance=RequestContext(request))

def faq(request):
    return render_to_response('support/faq.html', context_instance=RequestContext(request))

def opensearch(request):
    response = render_to_response('support/opensearch.html', context_instance=RequestContext(request))
    response['Content-Type'] = "application/xhtml+xml; charset=utf-8"
    return response

def api_opensearch(request):
    if request.GET.has_key('keyword'):
        keyword = request.GET['keyword']
        if request.GET.has_key('search_language') and request.GET['search_language']:
            snippets = Snippet.all().filter('language', request.GET['search_language']).search(keyword).order('-published_at')
        else:
            snippets = Snippet.all().search(keyword).order('-published_at').fetch(50)
    else:
        if request.GET.has_key('search_language') and request.GET['search_language']:
            snippets = Snippet.all().filter('language', request.GET['search_language']).order('-published_at')
        else:
            snippets = Snippet.all().order('-published_at').fetch(50)
    data = []
    for s in snippets:
        tags = [t.name for t in s.get_tags()]
        data.append({'title':s.title, 'language':s.language, 'code':s.code, 'comment':s.comment, 'url':s.url, 'author':s.author.email, 'pubDate':s.published_at, 'tags':tags})
    return json_response(data)

def api_searchform(request):
    return render_to_response('support/api_searchform.html', context_instance=RequestContext(request))